import { createRouter, createWebHashHistory } from 'vue-router'
// 引入组件
import Login from '../views/Login.vue'  //可以将.. 换为 @
import MainBox from '../views/MainBox.vue'
// 导入routes模块
import RoutesConfig from './config'
// 访问store
import store from '../store/index'
// 导入认证工具
import { checkTokenValidity } from '../util/auth'

const routes = [
  // 登录路由
  {  
    path: "/login",
    name: "login",
    component: Login
  },
  // 全局
  {
    path: "/mainbox",
    name: "mainbox",
    component: MainBox,
    redirect: "/index",
    children: []
  }
  // mainbox的嵌套路由，后面根据权限动态添加
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 记录最后活动时间
let lastActivityTime = Date.now()

// 更新用户活动时间
const updateActivityTime = () => {
  lastActivityTime = Date.now()
}

// 监听用户活动
window.addEventListener('click', updateActivityTime)
window.addEventListener('keydown', updateActivityTime)
window.addEventListener('mousemove', updateActivityTime)
window.addEventListener('scroll', updateActivityTime)

// 路由拦截 - 每次路由跳转之前，都会执行回调函数
router.beforeEach(async (to, from, next) => {
  if (to.name === "login") {
    next()
  } else {
    // 如果授权(已经登录过了)  next()
    // 未授权，重定向到login
    if (!localStorage.getItem("token")) {
      next({
        path: "/login"
      })
    } else {
      // 检查token是否过期
      const currentTime = Date.now()
      const inactiveTime = currentTime - lastActivityTime
      
      // 如果用户超过30分钟未活动，检查token有效性
      if (inactiveTime > 30 * 60 * 1000) {
        const isValid = await checkTokenValidity()
        if (!isValid) {
          return next({ path: "/login" })
        }
        // 更新活动时间
        updateActivityTime()
      }
      
      // 防止死循环
      if (!store.state.isGetterRouter) {
        // 删除所有的嵌套路由
        // mainbox
        router.removeRoute("mainbox")

        ConfigRouter()
        next({
          path: to.fullPath
        })
      } else {
        next()
      }
    }
  }
})

const ConfigRouter = () => {
  if (!router.hasRoute("mainbox")) {
    router.addRoute({
      path: "/mainbox",
      name: "mainbox",
      component: MainBox,
      redirect: "/mainbox/index",
      children: []
    })
  }

  // 遍历config路由
  RoutesConfig.forEach(item => {
    checkPermission(item) && router.addRoute("mainbox", item)
  })

  // 改变isGetterRouter = true
  store.commit("changeGetterRouter", true)
}

const checkPermission = (item) => {
  if (item.requireAdmin) {
    return store.state.userInfo.role === 1
  }
  if (item.requireEditor) {
    return store.state.userInfo.role === 1 || store.state.userInfo.role === 2
  }
  if (item.requireRegular) {
    return store.state.userInfo.role === 1 || store.state.userInfo.role === 2 || store.state.userInfo.role === 3
  }
  return true
}

export default router
